package pw.hais.etgsh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.squareup.okhttp.Response;

import pw.hais.etgsh.R;
import pw.hais.etgsh.app.BaseActivity;
import pw.hais.etgsh.app.V;
import pw.hais.etgsh.dao.ArticleDao;
import pw.hais.etgsh.model.ArticleModel;
import pw.hais.http.Http;
import pw.hais.http.base.OnHttpListener;
import pw.hais.utils.EmptyUtil;
import pw.hais.utils.L;
import pw.hais.utils.SPUtils;
import pw.hais.view.TextHtmlImageView;

/**
 * 海涵，内涵图片、段子详情
 * Created by Hais1992 on 2015/12/16.
 */
public class ArticleDetailsActivity extends BaseActivity implements View.OnClickListener {
    public static String INTENT_CONTENT_Id_KEY = "INTENT_CONTENT_Id_KEY";
    private boolean isAutoBoFangYuYin = SPUtils.getObject(V.SP_IS_AUTO_START, Boolean.class, false);
    private TextView text_title;
    private TextView text_ct;
    private TextHtmlImageView text_content;
    private Button btn_next, btn_share;

    private SpeechSynthesizer mTts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_details);


        String id = getIntent().getStringExtra(INTENT_CONTENT_Id_KEY);
        if (EmptyUtil.emptyOfString(id)) {
            finish();
        }

        text_title = (TextView) findViewById(R.id.text_title);
        text_ct = (TextView) findViewById(R.id.text_ct);
        btn_next = (Button) findViewById(R.id.btn_next);
        btn_share = (Button) findViewById(R.id.btn_share);
        btn_next.setOnClickListener(this);
        btn_share.setOnClickListener(this);
        text_content = (TextHtmlImageView) findViewById(R.id.text_content);


        loadDialogShow("数据加载中...");
        ArticleDao.getModelById(id, new OnHttpListener<ArticleModel>() {
            @Override
            public void onSuccess(Response response, ArticleModel data) {
                loadDialogDismiss();
                getSupportActionBar().setTitle(data.title);
                text_title.setText(data.title);
                text_ct.setText("来源：网络收集");
                text_content.setHtml(data.content);
                if (data.urls != null && data.urls.size() > 0) {
                    loadPageData(data);
                }else if(isAutoBoFangYuYin)startBoFangYuYin();
            }
        });

    }

    private int page = 0;

    private void loadPageData(final ArticleModel articleModel) {
        if (page >= articleModel.urls.size()){
            if(isAutoBoFangYuYin)startBoFangYuYin();
            return;
        }
        //获取数据
        Http.get(articleModel.urls.get(page), null, new OnHttpListener<String>() {
            @Override
            public void onSuccess(Response response, String data) {
                //解析内容
                ArticleDao.doArticleHtmlToItemModel(articleModel.id, data, new OnHttpListener<ArticleModel>() {
                    @Override
                    public void onSuccess(Response response, ArticleModel data) {
                        text_content.append(Html.fromHtml(data.content));
                        page = page + 1;
                        loadPageData(articleModel);
                    }
                });

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                setResult(333);
                finish();
                break;
            case R.id.btn_share:
                String title = text_title.getText().toString();
                String content = text_content.getText().toString();

                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "Share");
                intent.putExtra(Intent.EXTRA_TEXT, "【" + title + "】\n\n" + content + "...\n\n\t\t\t\t\t来自：儿童故事会");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(Intent.createChooser(intent, "分享"));
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_article_details, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_share) {
            isAutoBoFangYuYin = !isAutoBoFangYuYin;
            SPUtils.saveObject(V.SP_IS_AUTO_START, isAutoBoFangYuYin);
            if(isAutoBoFangYuYin){
                L.showShort("设置已改为自动播放！");
                startBoFangYuYin();
            }else{
                if(mTts!=null)mTts.destroy();
                L.showShort("播放已停止！");
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mTts!=null)mTts.destroy();
    }

    private void startBoFangYuYin(){
        mTts = SpeechSynthesizer.createSynthesizer(context, null);
        mTts.setParameter(SpeechConstant.VOICE_NAME, SPUtils.getObject(V.SP_IS_YUYIN_RENWU, String.class, "xiaoyan"));
        mTts.setParameter(SpeechConstant.SPEED, SPUtils.getObject(V.SP_LANGDU_SUDU, Integer.class, 50)+"");
        mTts.setParameter(SpeechConstant.VOLUME, "80");
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        mTts.startSpeaking(text_title.getText() + "。" + text_content.getText().toString(), mSynListener);
    }

    private SynthesizerListener mSynListener = new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {

        }

        @Override
        public void onBufferProgress(int i, int i1, int i2, String s) {

        }

        @Override
        public void onSpeakPaused() {

        }

        @Override
        public void onSpeakResumed() {

        }

        @Override
        public void onSpeakProgress(int i, int i1, int i2) {
            if(i>=99){
                if(!SPUtils.getObject(V.SP_IS_AUTO_NEXT, Boolean.class, false))return;
                L.showShort("2秒后播放下一则故事");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mTts.destroy();
                        btn_next.performClick();
                    }
                },2000);
            }
        }

        @Override
        public void onCompleted(SpeechError speechError) {
            L.showShort("播放失败！" + speechError.getErrorDescription());
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {
        }
    };
}
